package com.hong;

import com.hong.qrpc.Request;
import com.hong.qrpc.ServiceDescriptor;
import com.hong.qrpc.utils.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理rpc暴露的服务
 *
 * @Author HQT
 * @Date 2022/7/10 15:01
 */
@Slf4j
public class ServiceManager {
    //管理服务的集合
    private Map<ServiceDescriptor, ServiceInstance> services;

    public ServiceManager() {
        this.services = new ConcurrentHashMap<>();
    }

    /**
     * 注册服务
     *
     * @param interfaceClass 接口的class
     * @param bean           接口的实现类对象
     */
    public <T> void register(Class<T> interfaceClass, T bean) {
        log.info("register service: {}", interfaceClass);
        Method[] methods = ReflectionUtils.getPublicMethods(interfaceClass);
        for (Method method : methods) {
            ServiceInstance sit = new ServiceInstance(bean, method);
            ServiceDescriptor sd = ServiceDescriptor.from(interfaceClass, method);
            services.put(sd, sit);
        }
    }

    /**
     * 查找一个服务
     *
     * @param request
     * @return
     */
    public ServiceInstance lookUp(Request request) {
        ServiceDescriptor sd = request.getServiceDescriptor();
        ServiceInstance res = services.get(sd);
        log.info("lookup!{}", res);
        return res;
    }
}
